package com.education.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.dto.CourseDto;
import com.education.result.R;
import com.education.service.edu.entity.*;
import com.education.service.edu.entity.form.CourseInfoForm;
import com.education.service.edu.entity.query.CourseQuery;
import com.education.service.edu.entity.vo.CoursePublishVo;
import com.education.service.edu.entity.vo.CourseVo;
import com.education.service.edu.entity.vo.WebCourseVo;
import com.education.service.edu.feign.OssFileService;
import com.education.service.edu.mapper.*;
import com.education.service.edu.service.CourseService;
import org.springframework.cache.annotation.Cacheable;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Lance
 * @since 2020-06-16
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CourseCollectMapper courseCollectMapper;
    @Autowired
    private OssFileService ossFileService;


    /**
     * 新增课程
     * @param courseInfoForm
     * @return
     */
    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {
        // 目标字段
        Course course = new Course();
        // 将目标字段拷贝到数据源
        BeanUtils.copyProperties(courseInfoForm, course);
        // 设置为草稿状态
        course.setStatus(Course.COURSE_DRAFT);
        // 保存课程基本消息
        baseMapper.insert(course);

        // 保存课程详情信息
        CourseDescription courseDescription = new CourseDescription();
        // 课程详情信息
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.insert(courseDescription);
        // 返回ID
        return course.getId();
    }

    /**
     * 根据ID查询课程信息
     * @param id
     * @return
     */
    @Override
    public CourseInfoForm getCourseInfoById(String id) {
        // 获取course数据
        Course course = baseMapper.selectById(id);
        if (course == null){return null;}
        // 获取courseDescription数据
        CourseDescription courseDescription = courseDescriptionMapper.selectById(id);

        // 组装成CourseInfoForm
        CourseInfoForm infoForm = new CourseInfoForm();
        BeanUtils.copyProperties(course, infoForm);
        if (courseDescription != null){
            BeanUtils.copyProperties(courseDescription, infoForm);
        }
        return infoForm;
    }

    /**
     * 更新课程信息
     * @param courseInfoForm
     */
    @Override
    public void updateCourseInfoById(CourseInfoForm courseInfoForm) {
        // 目标字段
        Course course = new Course();
        // 将目标字段拷贝到数据源
        BeanUtils.copyProperties(courseInfoForm, course);
        // 更新保存课程基本消息
        baseMapper.updateById(course);

        // 更新保存课程详情信息
        CourseDescription courseDescription = new CourseDescription();
        // 课程详情信息
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        int i = courseDescriptionMapper.updateById(courseDescription);
        // 判断如果没有值的会就会保存进去
        if(i == 0){
            courseDescriptionMapper.insert(courseDescription);
        }

    }

    /**
     * 根据ID获取课程发布信息
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        return baseMapper.selectCoursePublishVoById(id);
    }

    /**
     * 根据id发布课程
     * @param id
     * @return
     */
    @Override
    public boolean publishCourseById(String id) {
        Course course = new Course();
        // 根据ID修改设置好的值
        course.setId(id);
        // 课程发布时间
        course.setPublishTime(new Date());
        // 修改状态 [ 正常状态]
        course.setStatus(Course.COURSE_NORMAL);
        // 使用mybatis plus 自己的 mapperService 中的update方法 [ Boolean ]类型的
        return this.updateById(course);
    }

    /**
     * 分页课程列表
     * @param page 查询第几页
     * @param limit 每页记录数
     * @param courseQuery 查询对象
     * @return
     */
    @Override
    public IPage<CourseVo> selectPage(Long page, Long limit, CourseQuery courseQuery) {

        QueryWrapper<CourseVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("c.create_time");

        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();

        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("c.title", title);
        }

        if (!StringUtils.isEmpty(teacherId) ) {
            queryWrapper.eq("c.teacher_id", teacherId);
        }

        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.eq("c.subject_parent_id", subjectParentId);
        }

        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.eq("c.subject_id", subjectId);
        }

        Page<CourseVo> pageParam = new Page<>(page, limit);
        //放入分页参数和查询条件参数，mp会自动组装
        List<CourseVo> records = baseMapper.selectPageByCourseQuery(pageParam, queryWrapper);
        pageParam.setRecords(records);
        return pageParam;
    }

    /**
     * 删除封面：OSS
     * @param id
     */
    @Override
    public boolean removeCoverById(String id) {
        Course course = baseMapper.selectById(id);
        if(course != null) {
            String cover = course.getCover();
            if(!StringUtils.isEmpty(cover)){
                //删除图片
                R r = ossFileService.removeFile(cover);
                return r.getSuccess();
            }
        }
        return false;
    }

    /**
     * 根据ID删除课程信息
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeCourseById(String id) {

        //收藏信息：course_collect
        QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
        courseCollectQueryWrapper.eq("course_id", id);
        courseCollectMapper.delete(courseCollectQueryWrapper);

        //评论信息：comment
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("course_id", id);
        commentMapper.delete(commentQueryWrapper);

        //课时信息：video
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", id);
        videoMapper.delete(videoQueryWrapper);

        //章节信息：chapter
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        chapterMapper.delete(chapterQueryWrapper);

        //课程详情：course_description
        courseDescriptionMapper.deleteById(id);

        //课程信息：course
        return this.removeById(id);
    }

    /**
     * 课程列表
     * @param webCourseQuery
     * @return
     */
    @Override
    public List<Course> webSelectList(WebCourseQuery webCourseQuery) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        //查询已发布的课程
        queryWrapper.eq("status", Course.COURSE_NORMAL);
        if (!StringUtils.isEmpty(webCourseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", webCourseQuery.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(webCourseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", webCourseQuery.getSubjectId());
        }
        if (!StringUtils.isEmpty(webCourseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(webCourseQuery.getPublishTimeSort())) {
            queryWrapper.orderByDesc("publish_time");
        }
        if (!StringUtils.isEmpty(webCourseQuery.getPriceSort())) {
            if(webCourseQuery.getType() == null || webCourseQuery.getType() == 1){
                queryWrapper.orderByAsc("price");
            }else{
                queryWrapper.orderByDesc("price");
            }
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 获取课程信息并更新浏览量
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public WebCourseVo selectWebCourseById(String id) {
        //更新课程浏览数
//        Course course = baseMapper.selectById(id);
//        course.setViewCount(course.getViewCount() + 1);
//        baseMapper.updateById(course);

        // 根据ID更新访问数 [ 使用数据库自带的行锁解决并发问题 ]
        baseMapper.updateWiewCountById(id);
        //获取课程信息
        return baseMapper.selectWebCourseById(id);
    }

    /**
     * 获取首页最热门前8条课程数据 [ 使用redis缓存 ]
     * @return
     */
    @Cacheable(value = "index", key = "'selectHotCourse'")
    @Override
    public List<Course> selectHotCourse() {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("view_count");
        queryWrapper.last("limit 8");
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据课程ID查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseDto getCourseDtoById(String courseId) {
        return baseMapper.selectCourseDtoById(courseId);
    }

    /**
     * 修改课程销量
     * @param id
     */
    @Override
    public void updateBuyCountById(String id) {
        Course course = baseMapper.selectById(id);
        course.setBuyCount(course.getBuyCount() + 1);
        this.updateById(course);
    }


}
